import { getAccessToken, getRefreshToken } from '@/utils/auth'
import { refreshToken } from '@/api/user'
import {apiConfig} from '@/utils/apiConfig'
// 配置API接口地址
const timeout = 10000;


const request = config => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    config.header = config.header || {}
    if (getAccessToken() && !isToken) {
        config.header['Authorization'] = 'Bearer ' + getAccessToken()
    }

    // 设置租户ID，默认为1
    config.header['tenant-id'] = apiConfig.tenantId;

    // get请求映射params参数
    if (config.params) {
        let url = config.url + '?' + tansParams(config.params)
        url = url.slice(0, -1)
        config.url = url
    }

    return new Promise((resolve, reject) => {
        uni.request({
            method: config.method || 'get',
            timeout: config.timeout || timeout,
            url: config.baseUrl || apiConfig.baseUrl + apiConfig.baseApi + config.url,
            data: config.data,
            header: config.header,
            dataType: 'json',
            success: (res) => {
                // 打印响应数据

                // 检查业务状态码，0表示成功
                const code = res.data.code
                const msg = res.data.msg || '未知错误'

                if (code === 401) {
                    refreshToken({ refreshToken: getRefreshToken() }).then(res => {
                        if (res.data.code === 0) {
                            // 刷新成功，更新token
                            uni.setStorageSync('ACCESS_TOKEN', res.data.data.accessToken);
                            uni.setStorageSync('REFRESH_TOKEN', res.data.data.refreshToken)
                                // 重新发起原来的请求
                            config.header['Authorization'] = 'Bearer ' + res.data.data.accessToken;
                            config.header['refreshToken'] = res.data.data.refreshToken;
                            return uni.request({
                                method: config.method || 'get',
                                timeout: config.timeout || timeout,
                                url: config.baseUrl || apiConfig.baseUrl + apiConfig.baseApi + config.url,
                                data: config.data,
                                header: config.header,
                                dataType: 'json',
                            }).then(resolve).catch(reject);
                        }
                    }).catch(err => {
                        reject('401');
                    });
                } else if (code === 500) {
                    uni.showToast({
                        title: msg,
                        icon: 'none'
                    })
                    reject('500')
                } else if (code !== 0) { // 业务状态码不为0，表示业务失败
                    console.log('msg', code)
                    if (code !== 400) {
                        uni.showToast({
                            title: msg,
                            icon: 'none'
                        })
                    }
                    reject(new Error(msg || '未知错误'))
                } else {
                    resolve(res)
                }
            },
            fail: (err) => {
                let message = '未知错误'
                if (err.errMsg && err.errMsg.includes('timeout')) {
                    message = '系统接口请求超时'
                } else if (err.errMsg && err.errMsg.includes('fail')) {
                    message = '后端接口连接异常'
                }

                uni.showToast({
                    title: message,
                    icon: 'none'
                })

                reject(new Error(message))
            }
        })
    })
}

// 参数处理
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName]
        var part = encodeURIComponent(propName) + "="
        if (value !== null && value !== "" && typeof(value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']'
                        var subPart = encodeURIComponent(params) + "="
                        result += subPart + encodeURIComponent(value[key]) + "&"
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&"
            }
        }
    }
    return result
}

export default request
